

function Dish(id,name,price){
	this.id = id;
	this.name = name;
	this.price = price;
}

function buyDish(id,name,price) {
	var dish = new Dish(id,name,price);
	var tbody = document.getElementById("cartBody");
	var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4 && xhr.status == 200) {
				var result = xhr.responseText;
				var back = JSON.parse(result);
				if (back.status) {
					if(back.data == "firstAdd"){
						appendTr(tbody,dish);
					}else if(back.data == "secondAdd"){
						editInput(dish);
					}
					count();
				} else {
					alert("add failed");
				}
			}
		}
	xhr.open("post", "client/cart", true);
	xhr.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded");
	xhr.send("action=add&did="+ id);
}

function changePrice(id,price){
	var tr = document.getElementById(id);
    var tda = tr.childNodes[1].childNodes[0].value;
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4 && xhr.status == 200) {
			var result = xhr.responseText;
			var back = JSON.parse(result);
			if (back.status) {
			    if(tda <= 0){
			        tr.parentNode.removeChild(tr);
			    }else{
			        var a = tr.childNodes[2];
			        a.innerHTML = Number(tda) * Number(price);
			        count();
			    }
			} else {
				alert("add failed");
			}
		}
	}
xhr.open("post", "client/cart", true);
xhr.setRequestHeader("Content-type",
		"application/x-www-form-urlencoded");
xhr.send("action=update&did="+ id +"&count=" + tda);
}

function count(){
	var tbody = document.getElementById("cartBody");
	var total = document.getElementById("total");
	var trList = tbody.childNodes;
	var allCount = 0;
	for(var i = 0;i < trList.length;i++){
		allCount = Number(allCount) + Number(trList[i].childNodes[2].innerHTML);
	}
	total.innerHTML = allCount;
}

function appendTr(tbody,dish){
	var tr = document.createElement("tr");
	tr.setAttribute("id",dish.id);
	var tdName = document.createElement("td");
	var tdPrice = document.createElement("td");
	var tdInput = document.createElement("td");
	var input = document.createElement("input");
	
	tdName.innerHTML = dish.name;
	tdPrice.innerHTML = Number(dish.price);
	input.value = Number(1);
	//input.setAttribute("type","number");
	input.onkeyup = function(){changePrice(dish.id,dish.price)};
	tdInput.appendChild(input);
	tr.appendChild(tdName);
	tr.appendChild(tdInput);
	tr.appendChild(tdPrice);
	tbody.appendChild(tr);
}



function editInput(dish){
	var tr = document.getElementById(dish.id);
	var inputDom = tr.childNodes[1].childNodes[0];
	var priceDom = tr.childNodes[2];
	priceDom.innerHTML = Number(priceDom.innerHTML) + Number(dish.price);
	var inputDomVal = inputDom.value;
	inputDom.value = Number(inputDom.value) + 1;
	changePrice(dish.id,dish.price);
}